﻿namespace NTLib.Pipe.Streaming.Formats
{
    using Descriptors.Packages;
    using NTLib.Core.Attributes;
    using NTLib.Core.Component;
    using System;

    /// <summary>
    /// Simple protocol : [Size Data][Data]
    /// The data are converted using the Json format.
    /// </summary>
    /// <seealso cref="NTLib.Pipe.Streaming.Formats.JsonFormatter" />
    [Guid("2321b81d-cb22-4492-a693-f1a47a92cf74")]
    [ConcurrentComponent()]
    public class SimpleJsonPackageFormater : JsonPackageFormater
    {
        #region Fields

        private readonly SimpleHeaderPackage _protocolFormat = new SimpleHeaderPackage();

        #endregion

        #region Properties

        /// <summary>
        /// Gets the reader descriptor.
        /// </summary>
        public override IPackageDescriptor ReaderDescriptor
        {
            get { return this._protocolFormat; }
        }

        #endregion

        #region Methods

        /// <summary>
        /// Converts the data to bytes.
        /// And add a simple header composed by the size of the package that follow.
        /// </summary>
        /// <param name="data"></param>
        /// <param name="T"></param>
        /// <returns></returns>
        protected override byte[] ConvertDataToBytes(object data, Type T)
        {
            byte[] dataConvert = base.ConvertDataToBytes(data, T);
            byte[] fullData = new byte[sizeof(Int32) + dataConvert.Length];

            BitConverter.GetBytes(dataConvert.Length).CopyTo(fullData, 0);
            dataConvert.CopyTo(fullData, sizeof(Int32));

            return fullData;
        }

        #endregion
    }
}
